import { useEffect } from 'react';
import { useModel, useHistory, useLocation } from 'umi';

import useLogin from '@/hooks/useLogin';

export interface IEntryParam {
  // 纯净模式(没有左边菜单,顶部内容,顶部内容)
  pure?: string;
  // 其他系统的凭证
  authorization?: string;
  // 系统标识 1：凌霄 2：crm平台
  platform?: string;
  // 品牌
  brand?: 'PH' | 'KFC';
  // 需要跳转的路由
  redirect?: string;
  // 用户名 来源其他渠道（域账号）
  userName?: string;
  ticket?: string;
}

type TLocation = {
  query: IEntryParam;
};

// 定点登录
// SSO

export default function CrmLogin() {
  const { initialState, setInitialState } = useModel('@@initialState');
  const history = useHistory();
  const { CRMLogin } = useLogin();
  const {
    query: { pure, redirect, authorization, platform, brand, userName, ticket },
  } = useLocation() as unknown as TLocation;

  useEffect(() => {
    const redirectPage = decodeURIComponent(redirect || '/');
    const loginPath = `/login${redirect ? `?redirect=${redirect}` : ''}`;
    if (ticket) {
      CRMLogin({
        ticket: ticket,
      })
        .then((msg) => {
          if (!msg) {
            history.replace(loginPath);
            return;
          } else {
            history.replace('/welcome');
          }
        })
        .catch(() => {
          history.replace(loginPath);
          return;
        });
    } else {
      history.replace(loginPath);
      return;
    }
  }, [
    CRMLogin,
    authorization,
    brand,
    history,
    initialState,
    platform,
    pure,
    redirect,
    setInitialState,
    ticket,
    userName,
  ]);
  return null;
}
